package com.leetcode.partition8;

import java.util.Arrays;

/**
 * @author `RKC`
 * @date 2021/8/25 9:19
 */
public class LC718最长重复子数组 {

    public static int findLength(int[] nums1, int[] nums2) {
        return dynamicProgramming(nums1, nums2);
        // return dynamicProgrammingScrollArray(nums1, nums2);
    }

    public static void main(String[] args) {
        int[] nums1 = {1, 2, 3, 2, 1};
        int[] nums2 = {3, 2, 1};
        System.out.println(findLength(nums1, nums2));
    }

    private static int dynamicProgrammingScrollArray(final int[] nums1, final int[] nums2) {
        // dp[i]表示到i这有dp[i]个重复的子数组元素
        int[] dp = new int[nums2.length + 1];
        int answer = 0;
        for (int i = 1; i <= nums1.length; i++) {
            // 避免数据被覆盖，从后往前遍历
            for (int j = nums2.length; j > 0; j--) {
                if (nums1[i - 1] == nums2[j - 1])
                    dp[j] = dp[j - 1] + 1;
                else
                    dp[j] = 0;
                answer = Math.max(answer, dp[j]);
            }
        }
        System.out.println(Arrays.toString(dp));
        return answer;
    }

    private static int dynamicProgramming(final int[] nums1, final int[] nums2) {
        // dp[i][j]表示以下标i-1的nums1和以下标j-1的nums2，最长重复子数组的长度为dp[i][j]
        int[][] dp = new int[nums1.length + 1][nums2.length + 1];
        int answer = 0;
        for (int i = 1; i < dp.length; i++) {
            for (int j = 1; j < dp[i].length; j++) {
                if (nums1[i - 1] == nums2[j - 1])
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                else
                    dp[i][j] = 0;
                answer = Math.max(answer, dp[i][j]);
            }
        }
        Arrays.stream(dp).forEach(item -> System.out.println(Arrays.toString(item)));
        return answer;
    }
}
